//
//  AddCommonAddressView.swift
//  JiaoZiTaxi
//
//  Created by shanzachattha8@gmail.comArmy1122@ on 2025/5/25.
//

import SwiftUI
import MapKit
import AlertToast
struct AddCommonAddressView: View {
    
    @State private var successShow = false
    
    
    @Environment(\.dismiss) var dismiss
    
    @FocusState private var isFocused: Bool
    
    @State var address: AddressModel
    
    @State private var successShowName: Bool = false
    
    @State private var successShowAddress: Bool = false
    
    @State  private var name: String = ""
    
    @StateObject private var addressManager = MyAddressNetManager()
    
    private var editIndex: Int = -1

    init(){
        let emptyAddress =  AddressModel(id: "", name: "", longname: "", intro: "", phone: "", picture: "", openid: "", jianceHangye: "", address: "", status: 0, time: 0, share: 0, latitude: 0, longitude: 0, headavitor: "", owner: "", url: "", categoryCode: 0, orderss: 0, type: "", lang: "", laosPhone: "")
        self.address = emptyAddress
    }
    
    init(address: AddressModel ,editIndex: Int) {
        self.editIndex = editIndex
        self.address = address
        self._name = State(initialValue: address.name ?? "")
    }
        
   private var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: ViewModel.shared.lastLocation.latitude, longitude: ViewModel.shared.lastLocation.longitude),
        span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
    )
    
    var body: some View {
        
        NavigationView {
            
            VStack {
                // MARK: 右上角的关闭页面按钮
                HStack {
                    Button(action: {
                        dismiss()
                    }, label: {
                        HStack {
                            Image(systemName: "chevron.backward")
                                .foregroundColor(.black)
                        }
                    })
                    Spacer()
                }
                
                HStack(spacing:30){
                    Text("名称").font(.system(size: 14))
                    TextField("例如：家/公司/学校" ,text: $name).font(.system(size: 14)).foregroundColor(.black)
                        .focused($isFocused)
                        .foregroundColor(.accentColor)
                        .keyboardType(.default)
                }.frame(height: 44).padding(.top,15)
                Divider()
                NavigationLink(destination:   CoomonAddressManagerView(region: self.region, selectCoordinate:  CarOrder.shared.startPos!, selectType: "start") {address in
                    self.address = address
                }){
                    HStack(spacing:30){
                        Text("地址").font(.system(size: 14)).foregroundColor(.black)
                        Text(getAddresssName(model: self.address)).foregroundColor(.gray).font(.system(size: 14))
                        Spacer()
                        Image(systemName: "chevron.right")
                    }.frame(height: 44)
                }
                
                Divider()
                Spacer()
                Button {
                    
                  
                    if self.name == "" {
                        self.successShowName = true;
                        return
                    }
                    if self.address.longname != nil , let name = self.address.address{
                        self.address.address = self.address.longname
                    }
                    
                    self.address.name =  "\(self.name)"
                    if self.address.address == "" {
                        self.successShowAddress = true;
                        return
                    }
                    
                    if self.editIndex != -1 {
                        addressManager.deleteCommonAddress(index: self.editIndex)
                    }
                    addressManager.setCommonAddress(address: self.address)
                    dismiss()
                    
                } label: {
                    Text("保存地址")
                    .frame(maxWidth:.infinity,maxHeight:44)
                    .font(.system(size: 16,weight: .bold))
                    .foregroundColor(Color.themeColor())
                    .background(Color.backgroundColor())
                    .cornerRadius(10)
                }
            }
            .contentShape(Rectangle())
            .onTapGesture {
                self.isFocused = false
            }
            .toast(isPresenting: $successShowName, alert: {
                return AlertToast(type: .regular, title: String(localized: "请输入名称"))
            })
            .toast(isPresenting: $successShowAddress, alert: {
                return AlertToast(type: .regular, title: String(localized: "请选择地址"))
            })
            .padding(.horizontal,15)
            .padding(.vertical,15)
            
        }
        .navigationBarHidden(true)
    }
    
    
    func getAddresssName(model :AddressModel)->String{

        if let name = model.address{
            return name
        }
        
        if let name = model.longname{
            return name
        }
        
        if let name = model.latitude{
            return "\(model.latitude ?? 0),\(model.longitude ?? 0)"
        }
        return "请选择地址".localized()
    }
    
    var backButton: some View {
        Button(action: {
            dismiss()
        }) {
            HStack {
                Image(systemName: "chevron.backward").resizable()
            }
            .foregroundColor(.black)
        }
    }
}

